<?php
declare(strict_types=1);

namespace app\middleware;

use think\facade\Log;

class UserAuth extends BaseAuth
{
    public function handle($request, \Closure $next)
    {
        try {
            // 获取 token
            $token = $request->header('Authorization');
            if (!$token) {
                return json(['code' => 401, 'msg' => '请先登录']);
            }

            // 验证 token 并获取用户 ID
            $userId = $this->getUserId($token);
            if (!$userId) {
                return json(['code' => 401, 'msg' => '登录已过期,请重新登录']);
            }

            // 将用户 ID 注入到 request 中
            $request->userId = $userId;
            
            // 获取商户 ID (如果有)
            $merchantId = $this->getMerchantId($token);
            if ($merchantId) {
                $request->merchantId = $merchantId;
            }

            return $next($request);
            
        } catch (\Exception $e) {
            Log::error('User auth error: ' . $e->getMessage());
            return json(['code' => 401, 'msg' => '认证失败']);
        }
    }

    protected function getGuard(): string
    {
        return 'user';
    }
} 